# webpack5踩坑记录

# 库类型打包

指定umd类型

export设为default即可,不然window下找不到

output: {
  path: path.resolve(__dirname, '../dist'),
  filename: 'graph.js',
  // export to AMD, CommonJS, or window
  libraryTarget: 'umd',
  // the name exported to window
  library: 'UEDGraph',
  libraryExport: 'default',
  // 清除打包目录内容
  clean: true
},

# demo项目同步更新

实现库文件变动,demo项目自动更新的效果。

开始使用wepack-dev-server,一直报找不到导出的包,实在找不到办法,于是放弃。

改用webpack watch源代码更新后自动打包,使用live-serve监听dist文件夹变动后触发更新。

# 热更新失效

首先webpack-cli的版本需要降下来

"webpack": "^5.36.0",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.2",

启动命令得用以前的:

webpack-dev-server xxx

webpack.config.js需加上

target: 'web'

或者去掉browserList

# 引入umd模块

方式1:npm publish

通过发布后安装,可正常使用

方式2:npm link

库项目npm link后在demo项目中npm link name,引入

因库和demo项目在同一路径,这种方式不适用

方式3:使用插件@babel/plugin-transform-modules-umd

然后在babel.config.js添加这个plugin

module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset',
  ],
  plugins: ['@babel/plugin-transform-modules-umd'], //添加这行
};

未尝试

方式4:webpack alias

使用webpack配置路径名,直接引用源文件

resolve: {
  alias: {
    '@ued/graph': path.resolve(__dirname, '../src/index')
  }
},

页面正常引入即可

# css 自动添加前缀

首先安装插件

npm install autoprefixer postcss postcss-loader -D
复制代码

修改 webpack.base.js 配置文件

// 省略...
const autoprefixer = require('autoprefixer');

module.exports = {
  // 省略...
  module: {
    rules: [
      // 省略...
      {
        test: /\.(le|c)ss$/,
        exclude: /node_modules/,
        use: [
          // 省略...
          'less-loader',
          {
            loader: 'postcss-loader',
            options: {
              postcssOptions: {
                plugins: [
                  ["autoprefixer"],
                ],
              },
            },
          }
        ]
      },
    ]
  },
  // 省略...
}

# 打包进度条

使用webpackbar

npm i webpackbar -D


const WebpackBar = require('webpackbar');

plugins: [
  // 添加 进度条
  new WebpackBar()
]